<script>
  import VTabNav from './v-tab-nav';

  export default {
    name: 'VTabs',
    components: {
      VTabNav,
    },
    props: {
      type: String,
      activeName: String,
      closable: Boolean,
      addable: Boolean,
      value: {},
      editable: Boolean,
    },
    data() {
      return {
        currentName: this.value || this.activeName,
        panes: [],
      };
    },
    watch: {
      activeName(value) {
        this.setCurrentName(value);
      },
      value(value) {
        this.setCurrentName(value);
      },
      currentName() {
        if (this.$refs.nav) {
          this.$nextTick(() => {
            this.$refs.nav.scrollToActiveTab();
          });
        }
      },
    },
    methods: {
      handleTabClick(tab, tabName, event) {
        if (tab.disabled) return;
        this.setCurrentName(tabName);
        this.$emit('tab-click', tab, event);
      },
      handleTabRemove(pane, ev) {
        if (pane.disabled) return;
        ev.stopPropagation();
        this.$emit('edit', pane.name, 'remove');
        this.$emit('tab-remove', pane.name);
      },
      handleTabAdd() {
        this.$emit('edit', null, 'add');
        this.$emit('tab-add');
      },
      setCurrentName(value) {
        this.currentName = value;
        this.$emit('input', value);
      },
      addPanes(pane) {
        const index = this.$slots.default.filter(item => item.elm.nodeType === 1 && /\bv-tab-pane\b/.test(item.elm.className)).indexOf(pane.$vnode);
        this.panes.splice(index, 0, pane);
      },
      removePanes(item) {
        const panes = this.panes;
        const index = panes.indexOf(item);
        if (index > -1) {
          panes.splice(index, 1);
        }
      },
    },
    render() {
      const {
        type,
        handleTabClick,
        handleTabRemove,
        handleTabAdd,
        currentName,
        panes,
        editable,
        addable,
      } = this;

      const newButton = editable || addable
        ? (
            <span
              class="v-tabs__new-tab"
              on-click={ handleTabAdd }
            >
                <i class="v-icon-plus"></i>
            </span>
          )
        : null;

      const navData = {
        props: {
          currentName,
          onTabClick: handleTabClick,
          onTabRemove: handleTabRemove,
          editable,
          type,
          panes,
        },
        ref: 'nav',
      };

      return (
        <div class={{
          'v-tabs': true,
          'v-tabs--card': type === 'card',
        }}>
          <div class="v-tabs__header">
            {newButton}
            <v-tab-nav { ...navData }></v-tab-nav>
          </div>
          <div class="v-tabs__content">
            {this.$slots.default}
          </div>
        </div>
      );
    },
    created() {
      if (!this.currentName) {
        this.setCurrentName('0');
      }
    },
  };
</script>
